package com.mvp.shq.washer.ui.login;

import com.mvp.shq.washer.entity.result.BaseResult;
import com.mvp.shq.washer.entity.TokenBean;
import com.mvp.shq.washer.entity.User;
import com.mvp.shq.washer.http.BaseObserver;
import com.mvp.shq.washer.http.RxSchedulers;
import com.mvp.shq.washer.utils.SignUtils;
import com.mvp.shq.washer.utils.SpUtil;
import com.mvp.shq.washer.utils.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2017/8/19.
 */

public class LoginPresenter extends LoginConstract.Presenter {
    @Override
    public void onStart() {

    }

    @Override
    void login(String mobile, String pwd) {
        String timestamp = SignUtils.getTime();
        pwd = StringUtils.MD5(pwd);
        Map<String,String> map = new HashMap();
        map.put("mobile",mobile);
        map.put("pwd",pwd);
        map.put("timestamp",timestamp);
        String sign = SignUtils.getSignature(map);
        model.login(mobile,pwd,timestamp,sign)
                .compose(RxSchedulers.io_main())
                .subscribe(new BaseObserver<TokenBean>(view) {
                    @Override
                    protected void onSuccees(BaseResult<TokenBean> t) throws Exception {
                        if (!t.isError()){
                            SpUtil.setToken(t.getData().getToken());
                            User user = new User();
                            user.setId(t.getData().getUserId());
                            SpUtil.setUser(user);
                            view.loginSuccess();
                        }else {
                            view.loginFail(t.getMsg());
                        }
                    }

                    @Override
                    protected void onFailure(Throwable e, boolean isNetWorkError) throws Exception {
                        view.loginFail("登录失败:未知错误");
                    }
                });
    }
}
